package com.cwz.interceptor;


import com.cwz.exception.ErrorEnum;
import com.cwz.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wenZhen
 * @create 2024-08-17 8:54
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String method = request.getMethod();
        if (HttpMethod.OPTIONS.matches(method)) {
            //如果是预检请求  则直接放行
            return true;
        }
        String requestURI = request.getRequestURI();
        log.info("注册路径:{}",requestURI);
        if ("/api/user/register".equals(requestURI)||("/api/file/upload").equals(requestURI)||("/chat/completions").equals(requestURI)) {
            return true; // 直接放行注册请求
        }
        log.info("拦截器session:{}", request.getSession().getAttribute("user"));

        if (request.getSession().getAttribute("user") == null) {
            throw new ServiceException(ErrorEnum.LOGIN_EXPIPRATION);
        }

        return true;
    }

}
